<script setup lang="tsx">
import { enrollOrderApi, getExportEnrollExcelApi } from '@/api/Order'
// import { enrollOrderCountApi, enrollOrderApi, getExportEnrollExcelApi } from '@/api/Order'
import { businessListApi } from '@/api/merchantManagement'
import type { OrderListParams } from '@/api/Order/types'
import Detail from './components/Detail.vue'
import { ElButton } from 'element-plus'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useI18n } from '@/hooks/web/useI18n'
import { useTable } from '@/hooks/web/useTable'
import { formatTime } from '@/utils'
import { hasPermission as hasPermis } from '@/components/Permission/src/utils'
import {
  OrderStateDict,
  OrderTypeDict,
  SubOrderStateDict,
  VerifyTypeDict,
  dictToList
} from '@/utils/dict'

const { t } = useI18n()

const activeTab = ref(0)
let tabs = ref([
  {
    label: '全部',
    value: 0
  },
  {
    label: '待支付',
    value: 1
  },
  {
    label: '待核销',
    value: 2
  },
  {
    label: '核销中',
    value: 3
  },
  {
    label: '已核销',
    value: 7
  },
  {
    label: '已取消',
    value: 4
  },
  {
    label: '已完成',
    value: 5
  },
  {
    label: '已关闭',
    value: 6
  }
])

// const getGroupOrderCount = async () => {
//   if (!hasPermis('GET /order/getEnrollOrderCount')) {
//     return false
//   }
//   const res = await enrollOrderCountApi()
//   const numMap = res.data.reduce((map, item) => {
//     map[item.orderState] = item.num
//     return map
//   }, {})
//   const result = tabs.value.map((tab) => {
//     const num = numMap[tab.value]
//     return {
//       ...tab,
//       label: `${tab.label.replace(/\(.*?\)/, '')}(${num})`
//     }
//   })
//   tabs.value = result
//   console.log(tabs.value)
// }
// getGroupOrderCount()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const res = await enrollOrderApi({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      orderState: unref(activeTab) === 0 ? '' : unref(activeTab),
      ...unref(searchParams)
    })
    return {
      list: res.data.list || [],
      total: res.data.total || 0
    }
  }
})
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList } = tableMethods

const searchRef = ref()

const tabChange = (v) => {
  searchRef.value[0].reset()
  activeTab.value = v
  currentPage.value = 1
  searchParams.value = {}
  getList()
  // getGroupOrderCount()
}

const getBusinessList = async () => {
  if (!hasPermis('GET /business/page')) {
    allSchemas.searchSchema.at(7)!.hidden = true
    return []
  }
  const res = await businessListApi({
    pageNum: 1,
    pageSize: 9999
  })
  return res.data.list?.map((v) => ({
    label: v.businessShortName,
    value: v.id
  }))
}

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'expand',
    type: 'expand',
    search: {
      hidden: true
    },
    slots: {
      default: (data) => {
        const { row } = data
        return (
          <div class="ml-60px">
            <el-table data={row.adminOrderItems} border style="width: 70%">
              {/* <el-table-column prop="subOrderNo" label="子订单号" /> */}
              <el-table-column
                label="子订单号"
                formatter={(ros) => (
                  <div>
                    <span>{ros.subOrderNo}</span>
                    {ros.verifyType === 1 && (
                      <span
                        style={
                          'border: 1px solid #333;padding: 0 4px;margin-left: 6px;border-radius: 4px;'
                        }
                      >
                        票付通
                      </span>
                    )}
                  </div>
                )}
              />
              <el-table-column prop="goodsPrice" label="商品价格" />
              <el-table-column prop="merchantAmt" label="分账本金" />
              <el-table-column prop="returnAmt" label="返现金额" />
              <el-table-column prop="totalSubsidyAmt" label="分账补贴" />
              <el-table-column
                label="子订单状态"
                formatter={(ros) => <span>{SubOrderStateDict[ros.subOrderState]}</span>}
              />
              <el-table-column prop="merchantName" label="核销商户" />
              <el-table-column
                label="核销渠道"
                formatter={(ros) => <span>{VerifyTypeDict[ros.verifyType]}</span>}
              />
              <el-table-column prop="pftOrder" label="票付通订单号" />
              <el-table-column prop="agent1CommissionAmt" label="一级佣金" />
              <el-table-column prop="agent2CommissionAmt" label="二级佣金" />
              <el-table-column prop="verifyTime" label="核销时间" />
            </el-table>
          </div>
        )
      }
    }
  },
  {
    field: 'id',
    label: 'ID',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'orderNo',
    label: '订单编号',
    search: {
      componentProps: {
        placeholder: '请输入订单编号'
      }
    },
    form: {
      hidden: true
    },
    table: {
      width: 280,
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <span>{row.orderNo}</span>
              {row.isPft && (
                <span
                  style={
                    'border: 1px solid #333;padding: 0 4px;margin-left: 6px;border-radius: 4px;'
                  }
                >
                  票付通
                </span>
              )}
            </>
          )
        }
      }
    }
  },
  {
    field: 'activeTitle',
    label: '活动名称',
    search: {
      componentProps: {
        placeholder: '请输入活动名称'
      }
    },
    form: {
      hidden: true
    },
    table: {
      width: 220
    }
  },
  {
    field: 'orderUserMobile',
    label: '下单人',
    search: {
      componentProps: {
        placeholder: '请输入下单人手机号'
      }
    },
    form: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <div>{row.orderMobile}</div>
              <div>{row.orderNickName}</div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'verifyType',
    label: '核销渠道',
    search: {
      component: 'Select',
      componentProps: {
        options: dictToList(VerifyTypeDict)
      }
    },
    form: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'pftOrder',
    label: '票付通订单号',
    search: {
      componentProps: {
        placeholder: '请输入子订单编号'
      }
    },
    form: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'subOrderNo',
    label: '子订单编号',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'payPrice',
    label: '实付金额',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'orderPrice',
    label: '订单金额',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'discountAmt',
    label: '优惠金额',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'redPacketAmt',
    label: '红包',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'totalSubsidyAmt',
    label: '总补贴',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'totalReturnAmt',
    label: '总返现',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'agentNickName',
    label: '一级经纪人',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <div>{row.agentNickName}</div>
              <div>{row.agentMobile}</div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'agent2NickName',
    label: '二级经纪人',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <div>{row.agent2NickName}</div>
              <div>{row.agent2Mobile}</div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'commissionAmt',
    label: '推广权益',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      width: 220,
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              {row.promotionEquityType === 0 && <div class={'flex items-center'}>无</div>}
              {row.promotionEquityType === 1 && (
                <div class={'flex items-center'}>
                  {row.otherEquity ? `其他：${row.otherEquity}` : '无'}
                </div>
              )}
              {row.promotionEquityType === 2 && row.agent2Id === 0 && (
                <>
                  <div class={'flex items-center'}>
                    实际全核销佣金金额：{row.totalCommissionAmt}
                  </div>
                  <div class={'flex items-center'}>一级经纪人佣金：{row.agent1CommissionAmt}</div>
                </>
              )}
              {row.promotionEquityType === 2 && row.agent2Id > 0 && (
                <>
                  <div class={'flex items-center'}>
                    实际全核销佣金金额：{row.totalCommissionAmt}
                  </div>
                  <div class={'flex items-center'}>一级经纪人佣金：{row.agent1CommissionAmt}</div>
                  <div class={'flex items-center'}>二级经纪人佣金：{row.agent2CommissionAmt}</div>
                </>
              )}
            </>
          )
        }
      }
    }
  },
  {
    field: 'orderType',
    label: '订单类型',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <span>{row.orderType && OrderTypeDict[row.orderType]}</span>
            </>
          )
        }
      }
    }
  },
  {
    field: 'orderState',
    label: '状态',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <span>{row.orderState && OrderStateDict[row.orderState]}</span>
            </>
          )
        }
      }
    }
  },
  {
    field: 'orderTime',
    label: '下单时间',
    search: {
      component: 'DatePicker',
      componentProps: {
        type: 'datetimerange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'payTime',
    label: '支付时间',
    search: {
      component: 'DatePicker',
      componentProps: {
        type: 'datetimerange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'businessName',
    label: '所属商家',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'businessId',
    label: '所属商家',
    search: {
      component: 'Select',
      optionApi: async () => getBusinessList()
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'agent1Keyword',
    label: '一级经纪人',
    search: {
      componentProps: {
        placeholder: '请输入一级经纪人手机号、姓名'
      }
    },
    form: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'agent2Keyword',
    label: '二级经纪人',
    search: {
      componentProps: {
        placeholder: '请输入一级经纪人手机号、姓名'
      }
    },
    form: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      width: 120,
      slots: {
        default: (data: any) => {
          const row = data.row as OrderListParams
          return (
            <>
              <ElButton
                v-hasPermi="GET /order/detailEnrollOrder"
                type="primary"
                link
                onClick={() => details(row)}
              >
                查看详情
              </ElButton>
            </>
          )
        }
      }
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const searchParams = ref({})
const setSearchParams = (params: any) => {
  const { orderTime, payTime, ...rest } = params
  let orderTimeStart, orderTimeEnd, payTimeStart, payTimeEnd
  if (orderTime && orderTime.length > 0) {
    orderTimeStart = orderTime[0]
    orderTimeEnd = orderTime[1]
  }
  if (payTime && payTime.length > 0) {
    payTimeStart = payTime[0]
    payTimeEnd = payTime[1]
  }
  currentPage.value = 1
  searchParams.value = {
    orderTimeStart,
    orderTimeEnd,
    payTimeStart,
    payTimeEnd,
    ...rest
  }
  getList()
  // getGroupOrderCount()
}

const showDrawer = ref(false)

const detailId = ref(0)

const details = async (row: any) => {
  console.log(row)
  detailId.value = row.id
  showDrawer.value = true
}

const handleDownload = async (params: any) => {
  const { orderTime, payTime, ...rest } = params
  let orderTimeStart, orderTimeEnd, payTimeStart, payTimeEnd
  if (orderTime && orderTime.length > 0) {
    orderTimeStart = orderTime[0]
    orderTimeEnd = orderTime[1]
  }
  if (payTime && payTime.length > 0) {
    payTimeStart = payTime[0]
    payTimeEnd = payTime[1]
  }
  const currentDate = new Date()
  const time = formatTime(currentDate, 'yyyyMMddHHmmss')
  const num = Math.floor(Math.random() * 900000) + 100000
  const orderState = unref(activeTab) === 0 ? '' : unref(activeTab)
  const res = await getExportEnrollExcelApi({
    orderState,
    orderTimeStart,
    orderTimeEnd,
    payTimeStart,
    payTimeEnd,
    ...rest
  })
  const correctMimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  const url = window.URL.createObjectURL(new Blob([res.data], { type: correctMimeType }))
  let link = document.createElement('a')
  link.href = url
  link.download = `报名订单明细${time}${num}`
  link.style.display = 'none'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}
</script>

<template>
  <div class="flex w-100% h-100%">
    <ContentWrap class="flex-[3] ml-20px">
      <ElTabs v-model="activeTab" @tab-change="tabChange">
        <ElTabPane v-for="item in tabs" :key="item.value" :label="item.label" :name="item.value">
          <Search
            ref="searchRef"
            :schema="allSchemas.searchSchema"
            :show-download="!!hasPermis('GET /order/exportEnrollExcel')"
            @download="handleDownload"
            @reset="setSearchParams"
            @search="setSearchParams"
          />
          <Table
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :columns="allSchemas.tableColumns"
            :data="dataList"
            :loading="loading"
            :expand="true"
            @register="tableRegister"
            :pagination="{
              total
            }"
          />
        </ElTabPane>
      </ElTabs>
    </ContentWrap>

    <ElDrawer
      title="订单详情"
      v-model="showDrawer"
      direction="rtl"
      size="650px"
      @close="showDrawer = false"
    >
      <Detail v-if="showDrawer" :id="detailId" />
    </ElDrawer>
  </div>
</template>
